<template>
  <div class="loginOutBox">
    <div class="login-container">
      <div class="title-container">视频行为分析系统</div>

      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on" label-position="left">
        <el-form-item prop="username">
          <span class="svg-container">
            <svg-icon icon-class="user" />
          </span>
          <el-input
            ref="username"
            v-model="loginForm.username"
            placeholder="请输入用户名"
            name="username"
            type="text"
            tabindex="1"
            autocomplete="on"
          />
        </el-form-item>

        <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
          <el-form-item prop="password">
            <span class="svg-container">
              <svg-icon icon-class="password" />
            </span>
            <el-input
              :key="passwordType"
              ref="password"
              v-model="loginForm.password"
              :type="passwordType"
              placeholder="请输入密码"
              name="password"
              tabindex="2"
              autocomplete="on"
              @keyup.native="checkCapslock"
              @blur="capsTooltip = false"
              @keyup.enter.native="handleLogin"
            />
            <span class="show-pwd" @click="showPwd">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
        </el-tooltip>
      </el-form>

      <el-button :loading="loading" @click.native.prevent="handleLogin">LOGIN</el-button>

      <el-dialog title="Or connect with" :visible.sync="showDialog">
        Can not be simulated on local, so please combine you own business simulation! ! !
        <br><br><br>
        <social-sign />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { validUsername } from '@/utils/validate'
import SocialSign from './components/SocialSignin'
import { checkLicense } from '@/api/user' // 引入授权检查接口

export default {
  name: 'Login',
  components: { SocialSign },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('Please enter the correct user name'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('The password can not be less than 6 digits'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: 'admin',
        password: 'qwe123'
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {}
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
  },
  methods: {
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
    },
    showPwd() {
      this.passwordType = this.passwordType === 'password' ? '' : 'password'
      this.$nextTick(() => this.$refs.password.focus())
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          // 1. 先执行登录（获取Token）
          this.$store.dispatch('user/login', this.loginForm)
            .then(() => {
              // 2. 登录成功后，调用授权检查接口（此时已携带Token）
              return this.$store.dispatch('user/checkLicense')
            })
            .then(licenseValid => {
              // 打印授权检查的最终结果（布尔值：true/false）
              console.log('授权检查结果（是否有效）：', licenseValid)
              // 3. 根据授权状态跳转
              if (licenseValid) {
                // 授权有效：跳首页
                this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
              } else {
                // 授权过期：跳授权页
                this.$router.push('/authorize')
                this.$message.warning('账号授权已过期，请重新授权')
              }
              this.loading = false
            })
            .catch(error => {
              this.loading = false
              console.error('登录或授权检查失败', error)
              this.$message.error('登录失败，请重试')
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') acc[cur] = query[cur]
        return acc
      }, {})
    }
  }
}
</script>

<style lang="scss">
/* 原有样式保持不变 */
$bg:#283443;
$light_gray:#fff;
$cursor: #fff;
$none: rgba(255,255,255,0);

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input { color: $cursor; }
}

.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;
    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: #0063c9;
      height: 47px;
      caret-color: $cursor;
      &:-webkit-autofill, &:-webkit-autofill:hover, &:-webkit-autofill:focus, &:-webkit-autofill:active{
        box-shadow: 0 0 0px 1000px $none inset !important;
        -webkit-text-fill-color: #0063c9 !important;
        -webkit-transition-delay: 111111s;
        -webkit-transition: color 11111s ease-out, background-color 111111s ease-out;
      }
    }
  }
  .el-form-item {
    border: 1px solid rgba(7, 118, 255, 0.35);
    background: rgba(255, 255, 255, 0.36);
    border-radius: 5px;
    color: #0063c9;
    margin:0 10px;
    width:24%
  }
  .el-button{
    width:500px;
    height: 68px;
    background:linear-gradient(to right, rgba(225,239,255,0) 15%, rgba(225,239,255,0.1),  #c3dfff, rgba(225,239,255,0.1) ,  rgba(225,239,255,0) 85% );
    border: 1px solid;
    border-image: linear-gradient(to right, rgba(152,214,252,0) 10%,  #2d86eb, rgba(152,214,252,0) 90%) 1;
    margin-top:100px;
    font-size: 22px;
    color: #3185e3;
    border-radius: 0 !important;
  }
  .el-button:hover { background:linear-gradient(to right, rgba(225,239,255,0) , #c3dfff,  rgba(225,239,255,0) ); }
  .el-button:focus { background-color:  none; border-color:  none; }
}
</style>

<style lang="scss" scoped>
/* 原有样式保持不变 */
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;
.loginOutBox{
  height: 100%;
  width: 100%;
  background: linear-gradient( 40deg,  #0058bd 15%,  #abcdf7 50%,#0058bd 85%);
  mix-blend-mode: multiply;
  animation: bgMove 10s infinite;
  background-size: 130% 130%;
}
@keyframes bgMove {
    0% { background-position:  0% 0% }
    50% { background-position: 100% 50% }
    100% { background-position: 0% 0% }
}
.login-container {
  min-height: 100%;
  width: 100%;
  background: url('../../assets/loginTopBg.png') repeat-x;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  .login-form {
    width:80%;
    height: 144px;
    background:linear-gradient(to right, rgba(225,239,255,0) 15%, rgba(225,239,255,0.1),  #c3dfff,rgba(225,239,255,0.1) ,  rgba(225,239,255,0) 85% );
    border: 1px solid;
    border-image: linear-gradient(to right, rgba(152,214,252,0) 10%,  #2d86eb, rgba(152,214,252,0) 90%) 1;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 50px;
  }
  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;
    span {
      &:first-of-type { margin-right: 16px; }
    }
  }
  .svg-container {
    padding: 6px 5px 6px 15px;
    color: #0668cd;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }
  .title-container {
    font-size: 54px;
    color: #fff;
    font-weight: bold;
    text-shadow: #518ed4 6px 6px 6px;
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }
  @media only screen and (max-width: 470px) {
    .thirdparty-button { display: none; }
  }
}
</style>